import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/contract_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:ls_work/util/toast.dart';

class ElderContractPage extends StatefulWidget {
  final int? customerId;
  ElderContractPage({Key? key, this.customerId});
  @override
  _ElderContractPageState createState() => _ElderContractPageState();
}

class _ElderContractPageState extends State<ElderContractPage> {
  Contract contractModel = Contract();
  List<ContractInfo> feeRuleList = [];
  List<DiscountInfo> favorList = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String contractNo = contractModel.contractNo??"";
    String startDate = contractModel.startDate??"";
    String endDate = contractModel.endDate??"";
    String deposit = contractModel.deposit != null
        ? contractModel.deposit.toString()
        : '0.0';
    return Scaffold(
      appBar: AppBar(
        title: Text('合同信息'),
        elevation: 0.5,
      ),
      body: Container(
        padding: EdgeInsets.fromLTRB(12, 20, 12, 0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '合同编号： $contractNo',
                style: TextStyles.textDark16,
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                '合同开始时间：$startDate',
                style: TextStyles.textDark16,
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                '合同截止时间：$endDate',
                style: TextStyles.textDark16,
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                '预交押金：$deposit',
                style: TextStyles.textDark16,
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                '优惠政策：',
                style: TextStyles.textDark16,
              ),
              SizedBox(
                height: 10,
              ),
              favorList.length <= 0
                  ? Container(
                      width: ScreenUtil.getScreenW(context) - 24,
                      height: 100,
                      padding: EdgeInsets.all(12),
                      child: Center(
                        child: Text('暂无'),
                      ),
                      decoration: BoxDecoration(
                          color: Colours.bg_color,
                          borderRadius: BorderRadius.circular(4)),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:
                          favorList.map((f) => _favorListWidget(f)).toList(),
                    ),
              SizedBox(
                height: 20,
              ),
              // Text('特批政策：特批政策1：',style: TextStyles.textDark16,),
              // SizedBox(height: 10,),
              // Container(
              //   width: ScreenUtil.getScreenW(context) - 24,
              //   height: 100,
              //   decoration: BoxDecoration(
              //     color: Colours.bg_color,
              //     borderRadius: BorderRadius.circular(4)
              //   ),
              // ),
              SizedBox(
                height: 20,
              ),
              _rowItem(
                  title: '内容', orgin: '原价', discount: '优惠', finalMoney: '优惠后'),
              Container(
                // padding: EdgeInsets.all(20),
                width: double.infinity,
                // height: 120,
                color: Colours.bg_gray,
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: feeRuleList.map((f) {
                      return _rowItem(
                          title: f.feeName??"",
                          orgin: f.money.toString(),
                          discount: f.discount.toString(),
                          finalMoney: f.finalMoney.toString());
                    }).toList()),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {'customerId': widget.customerId};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.contractDetail, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Contract model = Contract.fromJson(map['data']);
            setState(() {
              contractModel = model;
              feeRuleList = model.feeRuleList??[];
              favorList = model.favorList??[];
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Widget _rowItem(
      {String? title, String? orgin, String? discount, String? finalMoney}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        _item(title??""),
        _item(orgin??""),
        _item(discount??""),
        _item(finalMoney??""),
      ],
    );
  }

  Widget _item(String title) {
    return Container(
        padding: EdgeInsets.only(top: 10, bottom: 5),
        color: Colours.bg_gray,
        width: (ScreenUtil.getScreenW(context) - 24) / 4,
        alignment: Alignment.center,
        child: Text(
          title,
          style: TextStyles.textDark14,
        ));
  }

  Widget _favorListWidget(DiscountInfo info) {
    String time = '';
    print('🍉' * 20);
    if (info.startDate == null) {
      time = '-';
    } else {
      time = "${info.startDate}-${info.endDate}";

    }
    return Container(
      width: ScreenUtil.getScreenW(context) - 24,
      padding: EdgeInsets.all(12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "${info.schemaTypeName}-${info.actName}",
            style: TextStyles.textBoldDark16,
          ),
          _favorItem(title: '有效期：', content: time),
          _favorItem(
              title: '优惠说明：',
              content: info.remark??'暂无'),
        ],
      ),
      decoration: BoxDecoration(
          color: Colours.bg_color, borderRadius: BorderRadius.circular(4)),
    );
  }

  Widget _favorItem({String? title, String? content}) {
    return Container(
      padding: EdgeInsets.only(top: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            title??"",
            style: TextStyles.textDark14,
          ),
          Expanded(
            child: Text(content??"", style: TextStyles.textGray14),
          )
        ],
      ),
    );
  }
}
